package com.lagou.dubbo.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.PriorityQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MonitorBean {
    private String method;
    private final int unit = 60 * 1000;
    private int rate = 5 * 1000;
    // 一分钟等于12个5秒
    private int last = 12;
    private AtomicInteger index = new AtomicInteger();
    //请求的时间序列
    private PriorityQueue<Long> queue = new PriorityQueue<>();
    private ScheduledExecutorService threadPool;
    private static Logger log = LoggerFactory.getLogger(MonitorBean.class);

    public MonitorBean(String method) {
        this(method, 5 * 1000);
    }
    public MonitorBean(String method, int rate) {
        this.rate = rate;
        last = unit / rate;
        this.method = method;
        threadPool = Executors.newScheduledThreadPool(4);
        threadPool.scheduleAtFixedRate(() -> {
            printCost();
        }, 0, 5, TimeUnit.SECONDS);
    }

    public MonitorBean addCost(long cost) {
        this.queue.add(cost);
        return this;
    }

    public void printCost() {
        // 如果大于阈值，证明已经到了1分钟，则打印tp90
        int size = queue.size();
        if (index.incrementAndGet() > last) {
            if (size == 0) {
                //log.info("等待下一次调度...");
            } else {
                // 以下开始打印tp90使用率，保险起见，加个锁
                synchronized (this) {
                    //queue.
                    double tp90 = size * 0.9;
                    Long[] arr = queue.toArray(new Long[]{});
                    long tmp90 = arr[(int) tp90];
                    log.info(method + " tp90:" + tmp90 + ",队列长度:" + size);
                    queue.clear();
                    index.set(0);
                }
            }

        } else {
            log.info(method + "等待下一次调度....:" + index + ",队列长度:" + size);
        }
    }

}
